package com.wang.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class TestAspect {
    public TestAspect() {
        System.out.println("创建TestAspect成功");
    }

    //定义切点
    //匹配com.wang包及其子包中所有类中的所有方法
    @Pointcut("within(com.wang..*)")
    public void cut() {
    }


    @Before("cut()")
    public void sayBeFore(JoinPoint joinPoint) {

//        String methodName = joinPoint.getSignature().getName();
//        System.out.println("Method " + methodName + " starts at "+new Date());

//        System.out.println("前置通知");
//        System.out.println("目标类：" + joinPoint.getTarget());
//        System.out.println("方法名：" + joinPoint.getSignature().getName());
//        System.out.println("方法参数：" + joinPoint.getArgs());
    }

    @After("cut()")
    public void sayAfter(JoinPoint joinPoint) {
//        String methodName = joinPoint.getSignature().getName();
//
//        System.out.println("Method " + methodName + " ends at " + new Date());
//        System.out.println("后置通知");
//        System.out.println("目标类：" + joinPoint.getTarget());
//        System.out.println("方法名：" + joinPoint.getSignature().getName());
//        System.out.println("方法参数：" + joinPoint.getArgs());
    }

    //环绕通知。
    @Around("cut()")
    public Object sayAround(ProceedingJoinPoint pjp) throws Throwable {
        String methodName = pjp.getSignature().getName();
        long start = System.currentTimeMillis();
        System.out.println("----Method " + methodName +"开始----" );
        Object result = pjp.proceed();//执行方法
        long end = System.currentTimeMillis();
        System.out.println("----Method " + methodName + "结束,"+ "耗时:"+ (end-start) +"----");
        return result;
    }

}
